import { Command } from 'commander';
import inquirer from 'inquirer';
import { logger } from '../utils/logger';
import { requireAuth } from '../utils/validation';
import { CLIError } from '../types';

export function collaborationCommands(program: Command): void {
  program
    .command('share <resource>')
    .description('Share a project or module')
    .option('--public', 'Make resource publicly accessible')
    .option('--org <org>', 'Share with specific organization')
    .option('-t, --type <type>', 'Resource type (project|module)', 'project')
    .action(async (resourceName: string, options) => {
      try {
        requireAuth();

        const { type, public: isPublic, org } = options;
        
        if (isPublic && org) {
          throw new CLIError('Cannot specify both --public and --org options');
        }

        let shareType = 'private';
        if (isPublic) {
          shareType = 'public';
        } else if (org) {
          shareType = 'organization';
        }

        const confirm = await inquirer.prompt([
          {
            type: 'confirm',
            name: 'share',
            message: `Share ${type} "${resourceName}" as ${shareType}${org ? ` with ${org}` : ''}?`,
            default: false
          }
        ]);

        if (!confirm.share) {
          logger.info('Sharing cancelled');
          return;
        }

        const spinner = logger.spinner(`Sharing ${type}...`);
        try {
          spinner.succeed();
          
          const shareUrl = `https://cmodel.io/shared/${type}s/${resourceName}?token=abc123`;
          logger.success(`${type.charAt(0).toUpperCase() + type.slice(1)} "${resourceName}" shared successfully!`);
          logger.info(`Share URL: ${shareUrl}`);
          
          if (shareType === 'public') {
            logger.info('This resource is now publicly accessible');
          } else if (shareType === 'organization') {
            logger.info(`Shared with organization: ${org}`);
          } else {
            logger.info('Private share link created');
          }
        } catch (error) {
          spinner.fail();
          throw error;
        }
      } catch (error) {
        if (error instanceof CLIError) {
          throw error;
        }
        throw new CLIError('Failed to share resource');
      }
    });

  program
    .command('fork <project>')
    .description('Fork a project to your workspace')
    .action(async (projectName: string) => {
      try {
        requireAuth();

        const answers = await inquirer.prompt([
          {
            type: 'input',
            name: 'newName',
            message: 'New project name:',
            default: `${projectName}-fork`,
            validate: (input: string) => {
              if (!input.trim()) {
                return 'Project name is required';
              }
              return true;
            }
          },
          {
            type: 'confirm',
            name: 'includeData',
            message: 'Include project data and configurations?',
            default: true
          }
        ]);

        const spinner = logger.spinner(`Forking project ${projectName}...`);
        try {
          spinner.succeed();
          
          logger.success(`Project "${projectName}" forked as "${answers.newName}"`);
          logger.info(`Use "cm project use ${answers.newName}" to switch to the forked project`);
          
          if (answers.includeData) {
            logger.info('All configurations and modules have been copied');
          } else {
            logger.info('Only project structure was copied');
          }
        } catch (error) {
          spinner.fail();
          throw error;
        }
      } catch (error) {
        if (error instanceof CLIError) {
          throw error;
        }
        throw new CLIError('Failed to fork project');
      }
    });

  program
    .command('clone <url>')
    .description('Import project from share URL')
    .action(async (shareUrl: string) => {
      try {
        requireAuth();

        if (!shareUrl.includes('cmodel.io/shared/')) {
          throw new CLIError('Invalid share URL');
        }

        const urlParts = shareUrl.split('/');
        const resourceType = urlParts[urlParts.indexOf('shared') + 1];
        const resourceName = urlParts[urlParts.indexOf('shared') + 2]?.split('?')[0];

        if (!resourceName) {
          throw new CLIError('Could not parse resource name from URL');
        }

        const answers = await inquirer.prompt([
          {
            type: 'input',
            name: 'localName',
            message: `Local name for imported ${resourceType.slice(0, -1)}:`,
            default: resourceName,
            validate: (input: string) => {
              if (!input.trim()) {
                return 'Name is required';
              }
              return true;
            }
          },
          {
            type: 'confirm',
            name: 'proceed',
            message: `Import ${resourceType.slice(0, -1)} "${resourceName}" as "${resourceName}"?`,
            default: true
          }
        ]);

        if (!answers.proceed) {
          logger.info('Import cancelled');
          return;
        }

        const spinner = logger.spinner(`Importing ${resourceType.slice(0, -1)}...`);
        try {
          spinner.succeed();
          
          logger.success(`${resourceType.slice(0, -1).charAt(0).toUpperCase() + resourceType.slice(1, -1)} "${resourceName}" imported as "${answers.localName}"`);
          
          if (resourceType === 'projects') {
            logger.info(`Use "cm project use ${answers.localName}" to switch to the imported project`);
          } else if (resourceType === 'modules') {
            logger.info(`Module "${answers.localName}" is now available for installation`);
          }
        } catch (error) {
          spinner.fail();
          throw error;
        }
      } catch (error) {
        if (error instanceof CLIError) {
          throw error;
        }
        throw new CLIError('Failed to import from share URL');
      }
    });
}